//
//  CirclePickerInProcessViewController.m
//  nonghubao
//
//  Created by Fenrir on 13-10-22.
//  Copyright (c) 2013年 Chongqing Nonghubao Co., Ltd. All rights reserved.
//

#import "CirclePickerInProcessViewController.h"
#import "InvitationOptionsViewController.h"
#import "JSONRequest.h"
#import "JMFBase.h"

@interface CirclePickerInProcessViewController ()<JSONRequestDelegate>

@end

@implementation CirclePickerInProcessViewController
@synthesize modifyMode = _modifyMode;
@synthesize friendUserId = _friendUserId;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _modifyMode = NO;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    //导航按钮右侧：确定
    UIButton* comfirmButton = [Helper buttonWithStyle:ButtonStyleNavigationComfirm];
    [comfirmButton addTarget:self action:@selector(comfirmButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = nil;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:comfirmButton];
    
    self.title = _L(@"vc_title_031");
    
    if (!_modifyMode) {
//        self.title = _L(@"vc_title_100");
    }
    else {
        
        
        [self relationWithME];
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 私有方法

- (void)relationWithME
{
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CIRCLE_MEMBER_RELATIONS];
    request.delegate = self;
    request.hudOn = YES;
    request.hudTitle = _L(@"title_loading_01");
    if (_friendUserId != nil) {
        [request setValue:_friendUserId forParameter:@"peopleId"];
    }
    
    [request setSuccessSelector:@selector(relationInfoDidRecived:)];
    [request asynchronous];
}

#pragma mark - 事件
- (void)backButtonEvent
{
    [super backButtonEvent];
    
    if (!_modifyMode) {
        
        [Helper clearCircleCache];
    }
    else {
        
        
    }
}

- (void)comfirmButtonEvent
{
    if (!_modifyMode) {
        NSMutableArray* names = [[NSMutableArray alloc] init];
        NSMutableArray* ids = [[NSMutableArray alloc] init];
        
        for (NSDictionary* circle in [self circlesWeGot]) {
            [names addObject:[circle objectForKey:@"name"]];
            [ids addObject:[NSNumber numberWithInteger:[[circle objectForKey:@"id"] integerValue]]];
        }
        
        if (ids.count == 0) {
            [Helper showAlertWithTitle:@"" andMessage:_L(@"alert_132")];
            return;
        }
        
        [Helper cacheCircleWithIds:ids andNames:names];
        
        InvitationOptionsViewController *invitationOptionsVC = [[InvitationOptionsViewController alloc] init];
        [self.navigationController pushViewController:invitationOptionsVC animated:YES];
    }
    else {
        
    }
}

#pragma mark - Table view data source

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
    NSNumber* selector = [self.indicators objectAtIndex:indexPath.row];
    ((UIImageView*)[cell.contentView.subviews objectAtIndex:1]).image = [selector boolValue] ? [UIImage imageNamed:@"com_icon_011"] : [UIImage imageNamed:@"com_icon_010"];
    return cell;
}

#pragma mark - JSONRequestDelegate

//某一好友与“我”的关系（即好友在我的哪些圈子下）请求成功
- (void)relationInfoDidRecived:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {

        for (int i = 0; i < self.dataSource.count; i++) {
            
            //根据外部传入值，做选中指示器_indicators的初始化
            BOOL selected = false;
            for (NSDictionary* c in (NSArray *)jmf.data) {
                
                if ([[c objectForKey:@"id"] integerValue] == [[[self.dataSource objectAtIndex:i] objectForKey:@"id"] integerValue]) {
                    selected = true;
                    break;
                }
            }
            //指示器根据selected的结果值来添加元素。_dataSource每添加一个，_indicators就添加一个
            [self.indicators addObject:[NSNumber numberWithBool:selected]];
        }
        
        [self.tableView reloadData];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:@"" andMessage:_L(@"title_networkunavailabe")];
}

@end
